﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics.Contracts;

namespace HeapProfiler
{
	static public class CmdLineExtractor
	{
		static void Main(String[] args)
		{
			if(args == null || args.Length < 1 || args.Length > 2)
				Usage();

			if(args.Length == 2 && args[0].Equals("/f"))
			{
				System.Xml.XmlReader rr = System.Xml.XmlReader.Create(new System.IO.StreamReader(args[1]), new System.Xml.XmlReaderSettings() {IgnoreWhitespace=true});
				Dictionary<string, HeapModel.ProgInfo.TypeIdentifier> typedict = new Dictionary<string,HeapModel.ProgInfo.TypeIdentifier>();
				Dictionary<string, HeapModel.ProgInfo.OffsetIdentifier> offsetdict = new Dictionary<string,HeapModel.ProgInfo.OffsetIdentifier>();
				HeapModel.ConcreteMemory.ConcreteHeap ch = HeapModel.ConcreteMemory.ConcreteHeap.ReadConcreteMemory(rr, typedict, offsetdict);

				HeapModel.RegionPartition.RegionGraph rawheap = HeapModel.RegionPartition.RegionGraph.Create_NoNorm(ch, new HashSet<HeapModel.ProgInfo.TypeIdentifier>(typedict.Values));
				rawheap.WriteDgml("./rawdump.dgml");

				HeapModel.RegionPartition.RegionGraph rg = HeapModel.RegionPartition.RegionGraph.Create(ch, new HashSet<HeapModel.ProgInfo.TypeIdentifier>(typedict.Values));
				rg.WriteDgml("./rgdump.dgml");
				Console.WriteLine("Done Read Heap File.");
			}
			else
			{
				String fname = null;
				String exefile;

				if(args.Length == 1)
					exefile = args[0];
				else
				{
					fname = args[0];
					exefile = args[1];
				}

				HeapProfiler.Rewriter.DoRewrite(exefile, fname);
			}
		}

		private static void Usage()
		{
			Console.WriteLine("Usage: CmdLineProfiler file.exe");
			System.Environment.Exit(1);
		}
	}
}
